<?php

App::uses('AppModel', 'Model');
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');

class User extends AppModel
{
    const ESTATUS_ACTIVO = 1;
    const ESTATUS_INACTIVO = 0;

    public $validate = array(
        'user' => array(
            'rule' => 'alphaNumeric',
            'required' => true,
            'message' => 'Usuario es requerido'),
        'pass' => array(
            'rule' => 'alphaNumeric',
            'required' => true,
            'message' => 'Contraseña es requerida')
    );

    public function getByUsernameAndPass($username, $pass)
    {
        $passwordHasher = new SimplePasswordHasher();
        $pass = $passwordHasher->hash($pass);
        $users = $this->findByUserAndPassAndEstatus($username, $pass, Usuario::ESTATUS_ACTIVO);
        return count($users) > 0 ? $users[0] : null;
    }

    public function beforeSave($options = array())
    {
        //if (!$this->id)
        {
            $passwordHasher = new SimplePasswordHasher();
            $this->data['User']['pass'] = $passwordHasher->hash($this->data['User']['pass']);
        }
    }

    public function insert($user, $pass)
    {
        $data = array();
        $data['user'] = substr($user, 0, 10);
        $data['pass'] = $pass;
        $data['status'] = self::ESTATUS_ACTIVO;
        try
        {
            $this->save($data);
        }
        catch (PDOException $e)
        {
            switch ($e->getCode())
            {
                case 23000:
                    break;
                default:
                    throw $e;
            }
        }
    }

    public function getDistinctRfc()
    {
        $users = $this->query("
            SELECT distinct rfc
            FROM recuperaciones");
        return $users;
    }

    public function getUserByName($name) 
    {
        $user = $this->find('all', array('conditions' => array('user' => $name)));
        return $user;
    }
}
